HTML Templates
aka
import html/template
The following description will assume that we’re templating HTML, but other formats can be
templated, too (such as text/template
).
There are a few parts to the templating system. There is the dynamic data, which fills up designated slots within the template.
Related to the data, is the template data struct, which provides the structure and description of the dynamic data. You cannot use any data that is not declared by the data struct.
type templateStruct struct {
..Fields..
}
Notice about Template Structs
The template itself can be package-level only, and thus lower-cased, but the struct fields must be exported, and thus uppercase.
There is the template string, which can be seen as the template itself—it contains the HTML code and structure, and defines the dynamic data slots.
templateString := `...html structure, using dynamic data slots as {{ .Fields }}...`
We also have the template definition. I think of it as the compiled template string.
templateDefinition, err := template.New("templateName").Parse(templateString)
// or use template.Must, which handles the error
templateDefinition := template.Must(template.New("templateName").Parse(templateString))
The final step consist of executing data against the template definition. I kind of think of this as finally rendering the template? The rendered template is added to a bytes.Buffer.
var buf bytes.Buffer
templateDefinition.Execute(&buf, templateStruct{..struct data..})
In summary, we have:
- the template data, which is defined by..
- the template struct, which defines the fields used by..
- the template string, which is used to create..
- the template definition, which is executed and yields..
- the executed/rendered output
In as few lines as possible, this would look something like:
type templateStruct struct {
..Fields..
}
templateString := `...html structure...`
var buf bytes.Buffer
template.Must(template.New("templateName").Parse(templateString))
.Execute(&buf, templateStruct{..struct data..})
Note: If you execute the template definition multiple times using the same buffer, the buffer will grow and contain as many rendered HTML structures as executions.